import * as c from '@/services/consts';
// import * as apiServer from '@/services/vpnServer';
import * as api from '@/services/checkTask';
import * as apiNode from '@/services/node';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  CheckCircleFilled,
  ClockCircleOutlined,
  CloseCircleFilled,
  EditOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Badge,
  Button,
  Col,
  Descriptions,
  List,
  message,
  Popconfirm,
  Row,
  Space,
  Tag,
  Tooltip,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import VpnServerBatchRemarkForm from './BatchRemarkForm';
import dayjs from 'dayjs';
import * as utils from '@/utils/utils';
import { ProFormSelect } from '@ant-design/pro-components';

type VpnServerFormProps = {
  visible: boolean;
  ver: string | undefined;
  groupId: string | undefined;
  onCancel: () => void;
  onCancelAndReload: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel, onCancelAndReload, ver, groupId } = props;

  if (!visible) {
    return null;
  }

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const { hasRight } = useModel('useAuthModel');
  const [myloading, setMyloading] = useState<boolean>(true);
  const [dataSource, setDataSource] = useState<API.VpnServerCheckReport | undefined>(undefined);
  const [selectIds, setSelectIds] = useState<any[]>([]);
  // const [formVisible, setFormVisible] = useState<boolean>(false);
  const [formNodeVisible, setFormNodeVisible] = useState<boolean>(false);
  const [formCdnVisible, setFormCdnVisible] = useState<boolean>(false);
  const [formBridgeVisible, setFormBridgeVisible] = useState<boolean>(false);
  const [takeCount, setTakeCount] = useState<number>(12);

  const [formBatchGroupVisible, setFormBatchGroupVisible] =
    useState<boolean>(false);
  const [formBatchRemarkVisible, setFormBatchRemarkVisible] =
    useState<boolean>(false);
  const [currentServer, setCurrentServer] = useState<API.VpnServer | undefined>(
    undefined,
  );
  const [currentNode, setCurrentNode] = useState<API.Node | undefined>(
    undefined,
  );
  const [serverChecks, setServerChecks] = useState<
    API.VpnServerCheckIpReport[] | undefined
  >(undefined);

  let tableGroupTitle: string = '';
  let tableGroupFont: string = 'normal';

  
  const {
    setXrayConfigPublish
  } = useModel('useGlobalModel', (model) => ({
    setXrayConfigPublish: model.setXrayConfigPublish,
  }));

  const loadData = async () => {
    const result = await api.report({ ver, groupId, type:'auto', count: takeCount});
    if (result && result.success) {
      setDataSource(result);
    }
    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, [takeCount]);

  const handleChangeStatus = async (status: boolean) => {
    if (selectIds.length < 1) return;
    // console.log({ keys: selectIds, status: status });
    // const result = await apiServer.status({ keys: selectIds, status: status });
    const result = await apiNode.status({ keys: selectIds, status: status });
    if (result && result.success === true) {
      setXrayConfigPublish(true);
      setSelectIds([]);
      actionRef.current?.clearSelected?.();
      setMyloading(true);
      loadData();
      // actionRef.current?.reload();
    }
  };

  const handleFormBatchGroupSubmit = async (groupIds: string[]) => {
    // console.log({ keys: selectIds, groupIds: groupIds });
    // result = await apiServer.groups({ keys: selectIds, groupIds: groupIds });    
    const result = await apiNode.groups({ keys: selectIds, groupIds: groupIds });
    if (result && result.success === true) {
      setXrayConfigPublish(true);
      actionRef.current?.clearSelected?.();
      setFormBatchGroupVisible(false);
      setMyloading(true);
      loadData();
      // actionRef.current?.reload();
    }
  };

  const handleFormBatchRemarkSubmit = async (remark: string) => {
    let result: API.Result;
    // result = await apiServer.remarks({ keys: selectIds, remark: remark });
    result = await apiNode.remarks({ keys: selectIds, remark: remark });
    if (result && result.success === true) {
      actionRef.current?.clearSelected?.();
      setFormBatchRemarkVisible(false);
      // setMyloading(true);
      // loadData();
      // actionRef.current?.reload();
    }
  };
  
  const handleNodeFormSubmit = async (record: API.Node) => {
    let result: API.Result | undefined = undefined;
    if (currentNode) {
      result = await apiNode.update({
        ...currentNode,
        ...record,
      });
    }

    if (result && result.success === true) {
      setXrayConfigPublish(true);
      setCurrentNode(undefined);
      setFormNodeVisible(false);
      setFormCdnVisible(false);
      setFormBridgeVisible(false);
      setMyloading(true);
      loadData();
    }
  };

  const handleRemove = async (ver: string | undefined) => {
    if (!ver) {
      message.error('无效版本号');
      return;
    }
    const result = await api.remove({ ver: ver });
    if (result.success) {
      onCancelAndReload();
    }
  };

  const clientColumns: ProColumns<API.VpnServerCheckProgress>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      sorter: true,
      search: false,
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '在线',
      align: 'center',
      width: 60,
      dataIndex: 'online',
      sorter: true,
      search: false,
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '检测客户端',
      width:200,
      dataIndex: 'clientName',
      render: (_, record) => {
        return `${record.clientName} [${record.client}]`;
      },
    },
    {
      title: '检测客户端IP',
      dataIndex: 'ip',
      width:250,
      render: (_, record) => {
        return <>{record.ip} {record.network ? <Tag color='blue'>{record.network}</Tag> : ''}</>;
      },
    },
    {
      title: '进度',
      dataIndex: 'percent',
      width:80,
      render: (_, record) => {
        if (record.percent == 100) {
          return '完成';
        } else {
          return `${record.percent} %`;
        }
      },
    },
    {
      title: '开始时间',
      dataIndex: 'createTime',
    },
    {
      title: '最后更新时间',
      dataIndex: 'updateTime',
    },
  ];


  const columns: ProColumns<API.VpnServerCheckServer>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'serverStatus',
      hideInTable:!(dataSource?.job == "checknode" || dataSource?.job == "speedtest"),
      //sorter: (a, b) => (a.serverStatus == true ? 1 : 0) - (b.serverStatus == true ? 1 : 0),
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '分组',
      dataIndex: 'groupNames',
      width: 150,
      hideInTable:!(dataSource?.job == "checknode" || dataSource?.job == "speedtest"),
      render: (_, record) => {
        let text = '';
        if (record.groupNames) {
          text = record.groupNames.join(',');
        }
        if (tableGroupTitle != text) {
          tableGroupFont = tableGroupFont == 'blue' ? 'green' : 'blue';
        }
        tableGroupTitle = text; //'bolder'
        // return <div style={{color:tableGroupFont}}><div>{text}</div>{record.protocol ? <Tag>{c.getObjectText(c.VpnGroupProtocols, record.protocol)}</Tag>: ""}</div>;
        return (
          <div style={{ color: tableGroupFont }}>
            {record.protocol ? (
              <div>{c.getObjectText(c.VpnGroupProtocols, record.protocol)}</div>
            ) : (
              ''
            )}
            <div>{text}</div>
          </div>
        );
      },
    },
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      width: 200, //80
      hideInTable:!(dataSource?.job == "checknode" || dataSource?.job == "speedtest"),
      render: (_, record) => {
        return (
          <>
            <div>{record.instanceId}</div>
            <div>{record.name}</div>
          </>
        );
      },
    },
    // {
    //   title: '名称',
    //   dataIndex: 'name',
    //   width: 230,
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInTable:!(dataSource?.job == "checknode" || dataSource?.job == "speedtest"),
      width: 100,
      ellipsis: true,
      render: (_, record) => {
        return record.server?.remark;
      },
    },
    {
      title: '检测结果',
      dataIndex: 'groupNames',
      render: (_, record) => {
        if (!record.data) {
          return <></>;
        }
        let instCheckIps: API.VpnServerCheckIpReport[] = [];
        return record.data.map((item) => {
          let instCheckIp: API.VpnServerCheckIpReport = {
            client: item.ip,//item.bindIp,
            ping: true,
          };
          instCheckIps.push(instCheckIp);
          return (
            <List
              itemLayout="horizontal"
              dataSource={[item]}
              renderItem={(itemIp, index) => (
                <List.Item>
                  <List.Item.Meta style={{marginTop:-18}}
                    title={
                      <Space style={{color:'#777'}}>
                      {/* <Tag style={{ margin: 0 }}>IP</Tag> */}
                      <b>{item.ip}</b>
                      {hasRight('node_update') && (dataSource?.job == "checknode" || dataSource?.job == "speedtest") ? (
                        <a
                          onClick={(e) => {
                            if(record.node?.type == c.NodeType.Node.value){
                              setFormNodeVisible(true);
                              setCurrentNode(record.node);
                            }
                            else if(record.node?.type == c.NodeType.Cdn.value){
                              setFormCdnVisible(true);
                              setCurrentNode(record.node);
                            }
                            else if(record.node?.type == c.NodeType.Bridge.value){
                              setFormBridgeVisible(true);
                              setCurrentNode(record.node);
                            }
                          }}
                        >
                          {' '}
                          <EditOutlined />
                        </a>
                      ) 
                      : ''}</Space>
                    }
                    description={
                      <>

                      <Descriptions layout="vertical" column={item.schedules.length>12?12:item.schedules.length}>

                        {item.schedules?.map((val)=>{
                          return <Descriptions.Item label={`${utils.formatDate(val.date,'MM-DD HH:mm')}`}><Row gutter={1} style={{maxWidth:110}}>
                            {val.data?.map((rep) => {
                            instCheckIp.ping = instCheckIp.ping && rep.ping ? true : false;
                            return (
                              <Col>
                              <Tooltip title={<div style={{maxWidth:900, maxHeight:600, overflow:'auto'}}>{rep.logData.map((c)=><div>{c}</div>)}</div>} overlayStyle={{minWidth:600, maxWidth: 900}}>
                                  <Tag color={rep.ping == true ? 'success' : 'error'} style={{marginRight:-3,width:100}}>
                                    <b>{rep.client}</b>{rep.delay == 0 ? <span style={{color:'red'}}>&nbsp;0ms</span> : rep.delay > 0 ? <span style={{color:'#999'}}>&nbsp;{rep.delay}ms</span> :''}
                                  </Tag></Tooltip>
                                  

                                {dataSource.job == "speedtest" ? 
                                  <Space>
                                  <Tag style={{marginRight:4}}>
                                    <ArrowDownOutlined />
                                    {utils.formatRateBit(rep.download)}
                                    &nbsp;
                                    <ArrowUpOutlined />
                                    {utils.formatRateBit(rep.upload)}
                                  </Tag>
                                    <Tooltip title={<div style={{maxWidth:300, maxHeight:600, overflow:'auto'}}>
                                      <div>测速服务器国家：{rep.serverCountry}</div>
                                      {/* <div>测速服务器距离：{rep.serverDistance}</div>
                                      <div>测速服务器延迟：{rep.serverLatency}</div> */}
                                      <div>测速服务器出口IP：{rep.exportIp}</div>
                                      </div>} overlayStyle={{minWidth:300, maxWidth: 900}}>
                                      <InfoCircleOutlined />
                                    </Tooltip>
                                  </Space> : ''}
                                </Col>);
                            })}  
                          </Row>                          
                          </Descriptions.Item>
                        })}
                      </Descriptions>
                    
                    </>
                    }
                  />
                </List.Item>
              )}
            />
          );
        });
      },
    },
  ];

  return (
    <DrawerForm<API.VpnServerCheckModel>
      open={visible}
      title={
        <>
          检测结果 <Tag color="blue">版本：{dataSource?.ver}</Tag>{' '}
          <Tag color={utils.getTextRanColor(dataSource?.job ?? '')}>{dataSource?.job}</Tag>
          {dataSource?.mode ? <Tag color={utils.getTextRanColor(dataSource?.mode ?? '')}>{dataSource?.mode == 'detailed' ? '详细' : '快速'}</Tag> : ''}
          <Tag color="blue">
            下发时间：
            {dayjs(dataSource?.createTime).format('YYYY-MM-DD HH:mm:ss')}
          </Tag>{' '}
          <Tag color="blue">创建人：{dataSource?.createUser}</Tag>
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1500}
      // onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
    >
      {/* <ProTable<API.VpnServerCheckProgress>
        rowKey="client"
        actionRef={actionRef}
        loading={myloading}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={clientColumns}
        expandable={undefined}
        dataSource={dataSource?.progresss}
      /> */}

      <ProTable<API.VpnServerCheckServer>
        rowKey="serverId"
        actionRef={actionRef}
        headerTitle={
          <b>            
            <ProFormSelect
              name="takeTimes"
              label="查看自动检测记录数"
              allowClear={false}
              options={[
                {label:'近3次',value:3},
                {label:'近12次',value:12},
                {label:'近24次',value:24},
                {label:'近48次',value:48},
                {label:'近120次',value:120},
              ]}
              initialValue={takeCount}
              fieldProps={{
                onChange(value, option) {
                  setTakeCount(value);
                },
              }}
            />
            {dataSource?.checkConfig?.uncheckBlock == true ? (
              <Tag color="blue">不检测被墙</Tag>
            ) : (
              ''
            )}
          </b>
        }
        loading={myloading}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={columns}
        expandable={undefined}
        dataSource={dataSource?.data}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                }}
              >
                <span>
                  <Popconfirm
                    key="delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemove(dataSource?.ver);
                    }}
                  >
                    <Button type="primary">删除当前检测</Button>
                  </Popconfirm>
                </span>
                <span>
                  <a
                    target="_blank"
                    key="excel"
                    href={`/admin-api/vpnservercheck/export?ver=${
                      ver ? ver : dataSource?.ver
                    }`}
                  >
                    <ArrowDownOutlined />
                    下载Excel
                  </a>
                </span>
              </Space>
            </>
          ),
        }}
        rowSelection={!(dataSource?.job == "checknode" || dataSource?.job == "speedtest") ? false : {
          defaultSelectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectIds(selectedRowKeys);
          },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>

            <span>
              {hasRight('node_update') ? (
                <Popconfirm
                  key="disableStatus"
                  title="确定要批量禁用服务器？"
                  onConfirm={async () => {
                    handleChangeStatus(false);
                  }}
                >
                  <a>禁用</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('node_update') ? (
                <Popconfirm
                  key="enableStatus"
                  title="确定要批量启用服务器？"
                  onConfirm={async () => {
                    handleChangeStatus(true);
                  }}
                >
                  <a>启用</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('node_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchGroupVisible(true);
                  }}
                >
                  分组
                </a>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('node_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchRemarkVisible(true);
                  }}
                >
                  服务器备注
                </a>
              ) : (
                ''
              )}
            </span>
            
            <span>
                  <a
                    target="_blank"
                    key="export_excel_select"
                    href={`/admin-api/vpnservercheck/export?ver=${
                      ver ? ver : dataSource?.ver
                    }${selectIds?.map((val) => {return "&ids=" + val})}`}
                  >
                    <ArrowDownOutlined />
                    导出Excel
                  </a>
            </span>
          </Space>
        )}
      />

      <VpnServerBatchRemarkForm
        visible={formBatchRemarkVisible}
        onSubmit={handleFormBatchRemarkSubmit}
        onCancel={() => {
          setFormBatchRemarkVisible(false);
        }}
      />
    </DrawerForm>
  );
};

export default VpnServerForm;
